#!/usr/bin/env gosh
(use srfi-1)
(use sxml.ssax)
(use sxml.serializer)
(use sxml.tools)
(use sxml.sxpath)
(use gauche.sequence)
(use gauche.parseopt)

(define (main args)
  (let-args (cdr args)
      ((path-i  "i|itempath=s" "")
       (path-v "v|valuepath=s" "")
       (print-v "p" #f)
       (print-vonly "o" #f)
       (file "f|file=s" #f))
    (define sxml (if file
		   (call-with-input-file file (lambda (in)
						(ssax:xml->sxml in '())))
		   (ssax:xml->sxml (current-input-port) '())))
    (define path-value (sxpath "//mark/@v/text()"))
    (mark! sxml path-i path-v)
    ;;(mark! sxml "//td" "a/@href/text()"))
    (cond
     (print-v
       (for-each-with-index (lambda (i x)
			      (format #t "~a\t~d\n" x i))
			    (path-value sxml)))
     (print-vonly
      (for-each (lambda (x)
		  (format #t "~a\n" x))
		(path-value sxml)))
     (else (print (srl:sxml->html sxml))))))

(define (mark! sxml path-i path-v)
  (define path-item (sxpath path-i))
  (define path-value (sxpath path-v))
  (define (copy-node node)
    (let ((name (sxml:name node))
	  (attr-list (or (sxml:attr-list-node node) '(@ ())))
	  (content (sxml:content node)))
      `(,name ,attr-list ,@content)))
  (for-each-with-index (lambda (i x)
			 (let ((copy (copy-node x))
			       (value (path-value x)))
			   (sxml:change-name! x 'mark)
			   (sxml:change-attrlist! x `((value ,@value)))
			   (sxml:change-content! x (list copy))))
		       (path-item sxml)))
